package com.ruoyi.web.controller.video.api;

import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.video.domain.*;
import com.ruoyi.video.domain.vo.DataItem;
import com.ruoyi.video.domain.vo.DetailVo;
import com.ruoyi.video.domain.vo.UserVo;
import com.ruoyi.video.domain.vo.VideoRecordsVo;
import com.ruoyi.video.mapper.VideoDetailMapper;
import com.ruoyi.video.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
@Api("前端接口")
public class ApiController extends BaseController {

    @Autowired
    private IVideoCompanyService videoCompanyService;
    @Autowired
    private IVideoCompanyTemplateService companyTemplateService;
    @Autowired
    private IVideoTemplateService templateService;
    @Autowired
    private IVideoRecordsService videoRecordsService;
    @Autowired
    private IVideoDetailService detailService;
    @Autowired
    private VideoDetailMapper detailMapper;

    @ApiOperation("获取公司列表")
    @GetMapping("/getCompanylist")
    public List<VideoCompany> getCompanylist()
    {
        List<VideoCompany> videoCompanies = videoCompanyService.selectVideoCompanyList(null);
        return videoCompanies;
    }

    @ApiOperation("获取模板列表")
    @GetMapping("/getTemplatelist")
    public List<VideoTemplate> getTemplatelist()
    {
        SysUser sysUser = ShiroUtils.getSysUser();
        System.out.println("用户信息:" + sysUser.getLoginName());
        if(sysUser != null){
            Integer companyId = sysUser.getCompanyId();
            if(companyId != null){
                VideoTemplate videoTemplate = new VideoTemplate();
                videoTemplate.setCompanyId(companyId);
                return templateService.selectVideoTemplateList(videoTemplate);
            }
        }
//        return templateService.selectVideoTemplateList(null);
        return null;
    }


    @ApiOperation("获取模板详情数据")
    @GetMapping("/getTemplatelistById")
    public String getTemplatelistById(@RequestParam("userName")String userName,
                                      @RequestParam("sex")String sex,
                                      @RequestParam("templateId")Integer templateId) throws Exception{

        audio(templateId,userName,sex);
        List<VideoDetail> list = detailMapper.selectVideoDetailListAll(userName,sex,templateId);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        List<DetailVo> all = new ArrayList<>();

        List<VideoDetail> nullList = list.stream().filter(user->user.getUniqueNo() != null).collect(Collectors.toList());
        Map<String, List<VideoDetail>> map = nullList.stream()
                .collect(Collectors.groupingBy(VideoDetail::getUniqueNo));

        if(CollectionUtils.isNotEmpty(list)){
            list.forEach(e->{
                if(StringUtils.isNotBlank(e.getUniqueNo())){
                    List<VideoDetail> videoDetails = map.get(e.getUniqueNo());
                    if(CollectionUtils.isNotEmpty(videoDetails)){
                        DetailVo vo = new DetailVo();
                        List<String> textList = videoDetails.stream().map(user->user.getText()).collect(Collectors.toList());
                        List<String> audios = videoDetails.stream().map(user->user.getFilePath()).collect(Collectors.toList());
                        vo.setTexts(textList);
                        vo.setAudios(audios);
                        all.add(vo);
                        map.remove(e.getUniqueNo());
                    }
                }else {
                    List<String> textList = new ArrayList<>();
                    textList.add(e.getText());
                    List<String> audios = new ArrayList<>();
                    audios.add(e.getFilePath());
                    DetailVo vo = new DetailVo();
                    vo.setTexts(textList);
                    vo.setAudios(audios);
                    all.add(vo);
                }
            });
        }


//        List<String> textList = list.stream().map(user->user.getText()).collect(Collectors.toList());
//        List<String> audios = list.stream().map(user->user.getFilePath()).collect(Collectors.toList());
//        List<DataItem> dataList = Arrays.asList(new DataItem(textList,
//                audios),new DataItem(null,null));

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(all);
        return json;
    }

//    @ApiOperation("获取模板详情数据")
//    @GetMapping("/getTemplatelistById")
//    public VideoTemplateVo getTemplatelistById(@RequestBody UserVo userVo)
//    {
//        VideoDetail detail = new VideoDetail();
//        detail.setTemplateId(templateId);
//        List<VideoDetail> list = detailService.selectVideoDetailList(detail);
//        if(CollectionUtils.isEmpty(list)){
//            return null;
//        }
//        VideoTemplateVo vo = new VideoTemplateVo();
//        List<String> texts = new ArrayList<>();
//        List<String> path = new ArrayList<>();
//        for (VideoDetail videoDetail : list) {
//            texts.add(videoDetail.getText());
//            path.add(videoDetail.getFilePath());
//        }
//        vo.setTexts(texts);
//        vo.setPath(path);
//        vo.setDetailList(list);
//        return vo;
//    }

    @ApiOperation("添加记录")
    @PostMapping("/addRecord")
    @ResponseBody
    public AjaxResult addRecord(@ModelAttribute VideoRecordsVo videoRecords) {
        logger.info("开始添加记录>>>>>>>>>>>>>>>>>>>");
//        String pathPre = "/www/wwwroot/files/";
        String pathPre = "/www/wwwroot/qy.xunzhunshuju.com/videoFiles/";
        MultipartFile file = videoRecords.getFile();
        String fileName = "";
        if (file != null && !file.isEmpty()) {
            fileName = file.getOriginalFilename();
            try {
                file.transferTo(new File(pathPre + fileName));
            } catch (IOException e) {
                return error("上传异常");
            }
        } else {
            System.out.println("上传的文件为空");
        }
//        String fileName = FileUploadUtils.upload(pathPre, file);
        VideoRecords records = new VideoRecords();
        records.setSex(videoRecords.getSex());
        records.setFilePath(fileName);
        records.setUserName(videoRecords.getName());
        records.setEndTime(videoRecords.getEndTime());
        records.setStartTime(videoRecords.getStartTime());
        records.setTimeLength(videoRecords.getTimeLong());
        records.setTemplateId(videoRecords.getTemplateId());
        records.setBrowser(videoRecords.getBrowser());
        records.setChannel(videoRecords.getChannel());
        if(videoRecords.getTemplateId() != null){
            VideoTemplate videoTemplate = templateService.selectVideoTemplateById(videoRecords.getTemplateId());
            records.setCompanyId(videoTemplate.getCompanyId());
        }
        return toAjax(videoRecordsService.insertVideoRecords(records));
    }


    @ApiOperation("上传文件")
    @PostMapping("/uploadFile")
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        logger.info("开始上传文件>>>>>>>>>>>>>>>>>>>");
        String pathPre = "/www/wwwroot/qy.xunzhunshuju.com/videoFiles/";
        String fileName = "";
        if (file != null && !file.isEmpty()) {
            fileName = file.getOriginalFilename();
            try {
                file.transferTo(new File(pathPre + fileName));
                return success(fileName);
            } catch (IOException e) {
                return error("上传异常");
            }
        } else {
            System.out.println("上传的文件为空");
            return error("文件为空");
        }
    }

    @ApiOperation("添加记录")
    @PostMapping("/addRecordV2")
    @ResponseBody
    public AjaxResult addRecordV2(@RequestBody VideoRecordsVo videoRecords) {
        logger.info("开始添加记录>>>>>>>>>>>>>>>>>>>");
        VideoRecords records = new VideoRecords();
        records.setSex(videoRecords.getSex());
        records.setFilePath(videoRecords.getFileName());
        records.setUserName(videoRecords.getName());
        records.setEndTime(videoRecords.getEndTime());
        records.setStartTime(videoRecords.getStartTime());
        records.setTimeLength(videoRecords.getTimeLong());
        records.setTemplateId(videoRecords.getTemplateId());
        records.setBrowser(videoRecords.getBrowser());
        records.setChannel(videoRecords.getChannel());
        if(videoRecords.getTemplateId() != null){
            VideoTemplate videoTemplate = templateService.selectVideoTemplateById(videoRecords.getTemplateId());
            records.setCompanyId(videoTemplate.getCompanyId());
        }
        return toAjax(videoRecordsService.insertVideoRecords(records));
    }

    public void audio(Integer templateId,String userName,String sex){
        List<VideoDetail> videoDetails = detailMapper.selectVideoDetailListNull(templateId);
        String pathPre = "/www/wwwroot/qy.xunzhunshuju.com/audios/";
//        String pathPre = "/audios/";
//        String pathPre = "C:\\files\\video\\";
        if(CollectionUtils.isNotEmpty(videoDetails)){
            String API_KEY = "sk-73bee8e4fc8644eb99a76d302fbe40f9"; // 替换为你的API Key
            String MODEL = "cosyvoice-v1";      // 模型版本
            String VOICE = "longwan";   // 音色（参考音色列表[1](@ref)）

            videoDetails.forEach(e->{

                SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                        .apiKey(API_KEY)
                        .model(MODEL)
                        .voice(VOICE)
                        .speechRate(e.getSpeechRate())
                        .build();
                SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);



                String text = e.getText().replace("{userName}",userName).replace("{sex}",sex);
                String path = System.currentTimeMillis() + ".mp3";
                e.setText(text);
                e.setFilePath("https://qy.xunzhunshuju.com/audios/" + path);
                e.setUserName(userName);
                e.setSex(sex);
                e.setId(null);

                ByteBuffer audioData = synthesizer.call(text);

                List<VideoDetail> videoDetails1 = detailMapper.selectVideoDetailListOwn(userName, sex, templateId,e.getLevel());
                if(CollectionUtils.isEmpty(videoDetails1)){
                    try (FileOutputStream fos = new FileOutputStream(pathPre + path)) {
                        fos.write(audioData.array());
                        detailService.insertVideoDetail(e);
                        System.out.println("✅ 合成成功！文件保存至: " + pathPre + path);
                        System.out.println("🔧 请求ID: " + synthesizer.getLastRequestId());
                    } catch (Exception ex) {
                        System.err.println("❌ 保存失败: " + ex.getMessage());
                    }
                }
            });
//            String text = user.getName() + user.getGender() + "您通过今东云平台申请并办理了一笔多少元的中邮极速贷 车主专享";
//            String outputPath = "/www/wwwroot/qy.xunzhunshuju.com/default_1.mp3";
////        String outputPath = "C:\\Files\\default_1.mp3";
//            String text1 = "请问，" + user.getName() + user.getGender() + "，保证提供的材料是否真实有效。";
//            String outputPath1 = "/www/wwwroot/qy.xunzhunshuju.com/default_4.mp3";
//        String outputPath1 = "C:\\Files\\default_4.mp3";

//        String a = "本次贷款由中邮消金公司为您提供，陕西航卓融资担保有限公司为您的该笔贷款提供担保,您同意并确认以反担保保证人的身份自愿以所有的车辆做为抵押物问陕西航卓融资担保有限公司提供反担保抵押。\n" +
//                "您有逾期还款、如拆卸GPS或有二押行为的同意陕西航卓融资担保有限公司有权对您的车辆实施收车等暂管行为，\n" +
//                "该抵押行为与中邮消金无任何关系台州市鼎龙网络传媒科技公司只收取GPS安装服务费，不向您收取除此以外的任何费用，不支持不提倡您向其它任何第三方或个人支付费用。以上内容您是否清楚明白?";
//
//        String outputPath2 = "C:\\Files\\default_0.mp3";

//            SpeechSynthesisParam param = SpeechSynthesisParam.builder()
//                    .apiKey(API_KEY)
//                    .model(MODEL)
//                    .voice(VOICE)
//                    .build();
//
//            // 2. 初始化合成器
//            SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
//
//            // 3. 调用合成接口
////        String text = "欢迎使用阿里云CosyVoice语音合成！";
//            ByteBuffer audioData = synthesizer.call(text);
//
//            ByteBuffer audioData1 = synthesizer.call(text1);
//
////        ByteBuffer audioData2 = synthesizer.call(a);
//
//            // 4. 保存为MP3文件
//            try (FileOutputStream fos = new FileOutputStream(outputPath)) {
//                fos.write(audioData.array());
//                System.out.println("✅ 合成成功！文件保存至: " + outputPath);
//                System.out.println("🔧 请求ID: " + synthesizer.getLastRequestId()); // 用于排查问题[6](@ref)
//            } catch (Exception e) {
//                System.err.println("❌ 保存失败: " + e.getMessage());
//            }
//
//            try (FileOutputStream fos = new FileOutputStream(outputPath1)) {
//                fos.write(audioData1.array());
//                System.out.println("✅ 合成成功！文件保存至: " + outputPath1);
//                System.out.println("🔧 请求ID: " + synthesizer.getLastRequestId()); // 用于排查问题[6](@ref)
//            } catch (Exception e) {
//                System.err.println("❌ 保存失败: " + e.getMessage());
//            }
        }
    }


    @ApiOperation("登陆")
    @GetMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(@RequestParam(name = "username",required = true) String username,
                                @RequestParam(name = "password",required = true) String password)
    {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, false);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            return success();
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (com.ruoyi.common.utils.StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    public static void main(String[] args) {
        String API_KEY = "sk-73bee8e4fc8644eb99a76d302fbe40f9"; // 替换为你的API Key
        String MODEL = "cosyvoice-v1";      // 模型版本
        String VOICE = "longwan";   // 音色（参考音色列表[1](@ref)）

        SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                .apiKey(API_KEY)
                .model(MODEL)
                .voice(VOICE)
                .build();
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);

        String path = "C:\\Files\\video\\default_5.mp3";

        ByteBuffer audioData = synthesizer.call("具体还款计划以北银消金为准，清楚并认可本次贷款的息费吗？");

        try (FileOutputStream fos = new FileOutputStream(path)) {
            fos.write(audioData.array());
            System.out.println("✅ 合成成功！文件保存至: " + path);
            System.out.println("🔧 请求ID: " + synthesizer.getLastRequestId()); // 用于排查问题[6](@ref)
        } catch (Exception ex) {
            System.err.println("❌ 保存失败: " + ex.getMessage());
        }
    }

}
